<template>
  <Header/>
  <div class="personal-center container">
    <el-card class="profile-card" v-loading="loading">
      <div class="profile-content">
        <!-- 头像区域 -->
        <div class="avatar-section" style="text-align: center;">
          <el-upload
              action="#"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :auto-upload="false"
              :on-change="handleAvatarChange"
              accept="image/*"
          >
            <!-- 把头像区域放进 trigger slot 作为点击触发 -->
            <template #trigger>
              <el-avatar
                  :size="120"
                  :src="previewUrl || userStore.user.avatar_url || avatarImg"
                  style="cursor: pointer; border: 1px solid #dcdfe6;"
              >
                {{ userStore.user.username.charAt(0).toUpperCase() }}
              </el-avatar>
            </template>
          </el-upload>

          <div style="margin-top: 12px;">
            <el-button type="success" size="small" @click="confirmUploadAvatar" :disabled="!selectedAvatar">
              上传头像
            </el-button>
          </div>
        </div>

        <!-- 基本信息 -->
        <div class="info-section">
          <el-form label-width="100px" label-position="left">
            <el-form-item label="用户名">
              <el-input v-model="userStore.user.username" readonly></el-input>
            </el-form-item>

            <el-form-item label="昵称">
              <el-input
                  v-model="userStore.user.nickname"
                  placeholder="请输入昵称"
              ></el-input>
            </el-form-item>

            <el-form-item label="电子邮箱">
              <el-input
                  v-model="userStore.user.email"
                  placeholder="请输入邮箱"
              ></el-input>
            </el-form-item>

            <el-form-item label="手机号码">
              <el-input
                  v-model="userStore.user.phone"
                  placeholder="请输入手机号"
              ></el-input>
            </el-form-item>

            <el-form-item label="个人简介">
              <el-input
                  type="textarea"
                  :rows="3"
                  v-model="userStore.user.biography"
                  placeholder="请输入个人简介"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="action-buttons">
        <el-button type="primary" @click="saveProfile" :loading="saving">保存修改</el-button>
        <el-button @click="fetchUserInfo">重置</el-button>
      </div>
    </el-card>
  </div>
  <Footer/>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import {ElMessage} from 'element-plus';
import Header from "@/components/Header.vue";
import Footer from "@/components/Footer.vue";
import {useUserStore} from "@/stores/user.js";
import avatarImg from '@/assets/avatar.jpg';

const userStore = useUserStore();
const loading = ref(false);
const saving = ref(false);

// 上传头像
const selectedAvatar = ref(null);
const previewUrl = ref(null);
// 上传头像前验证
const beforeAvatarUpload = file => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isImage) ElMessage.error('只能上传图片文件');
  if (!isLt2M) ElMessage.error('图片大小不能超过 2MB');
  return isImage && isLt2M;
};
// 获取本地图片
const handleAvatarChange = ({raw}) => {
  selectedAvatar.value = raw;
  if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);
  previewUrl.value = URL.createObjectURL(raw);
};
// 上传图片
const confirmUploadAvatar = async () => {
  if (!selectedAvatar.value) return;
  loading.value = true;
  try {
    const formData = new FormData();
    formData.append('avatar', selectedAvatar.value);
    await userStore.toUpdateUserInfo(formData);
    await userStore.fetchUserInfo();
    ElMessage.success('头像上传成功');
  } catch {
    ElMessage.error('头像上传失败');
  } finally {
    loading.value = false;
    if (previewUrl.value) {
      URL.revokeObjectURL(previewUrl.value);
      previewUrl.value = null;
    }
    selectedAvatar.value = null;
  }
};


// 获取用户信息
const fetchUserInfo = async () => {
  try {
    loading.value = true;
    await userStore.fetchUserInfo();
  } catch (error) {
    ElMessage.error('获取用户信息失败');
  } finally {
    loading.value = false;
  }
};

// 保存个人信息
const saveProfile = async () => {
  try {
    saving.value = true;
    const {nickname, email, phone, biography} = userStore.user;

    await userStore.toUpdateUserInfo({nickname, email, phone, biography});
    ElMessage.success('个人信息更新成功');
  } catch (error) {
    ElMessage.error('更新失败: ' + (error.response?.data?.message || error.message));
  } finally {
    saving.value = false;
  }
};

// 初始化获取用户信息
onMounted(() => {
  fetchUserInfo();
});
</script>


<style scoped>
.personal-center {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.profile-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
}

.profile-content {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  flex: 0 0 200px;
}

.info-section {
  flex: 1;
  min-width: 300px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  gap: 20px;
}

@media (max-width: 768px) {
  .profile-content {
    flex-direction: column;
  }

  .avatar-section {
    margin-bottom: 20px;
  }
}
</style>